package com.snake.springboot.custom.service.impl.base;


import com.snake.springboot.custom.api.model.base.CustStrategySumModel;
import com.snake.springboot.custom.api.response.base.CustomRsp;
import com.snake.springboot.custom.api.service.base.CustomAssService;
import com.snake.springboot.custom.dao.mybatis.entity.base.CustCountDO;
import com.snake.springboot.custom.dao.mybatis.mappers.base.CustRoleMapper;
import com.snake.springboot.custom.dao.mybatis.mappers.base.CustSubAccountMapper;
import com.snake.springboot.custom.service.port.adapter.event.AuthStrategyEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>组装业务类
 * 类{@code CustomAssServiceImpl} </br>
 * 创建时间2025/3/13 14:47
 * @author yangxt
 * @see
 */
@Service
public class CustomAssServiceImpl implements CustomAssService {
    @Autowired
    private CustRoleMapper custRoleMapper;
    @Autowired
    private CustSubAccountMapper accountMapper;
    @Autowired
    private ApplicationContext context;

    @Override
    public void assertCustomList(List<CustomRsp> rspList) {
        if (rspList == null && rspList.isEmpty()) {
            return;
        }
        try {
            List<String> customIds = rspList.stream().map(CustomRsp::getCustomId).collect(Collectors.toList());
            Map<String, Integer> roleMap = custRoleMapper.querySumByCustomIds(customIds).stream().collect(Collectors.toMap(CustCountDO::getCustomId, CustCountDO::getSumCount));
            Map<String, Integer> subMap = accountMapper.querySumByCustomIds(customIds).stream().collect(Collectors.toMap(CustCountDO::getCustomId, CustCountDO::getSumCount));
            AuthStrategyEvent event = new AuthStrategyEvent(this, customIds);
            context.publishEvent(event);
            Map<String, Integer> strategyMap =event.getResult().stream().collect(Collectors.toMap(CustStrategySumModel::getOperatorId, CustStrategySumModel::getStrategySum));

            for (CustomRsp rsp : rspList) {
                //组装角色数量信息
                if (roleMap.containsKey(rsp.getCustomId())){
                    rsp.setRoleCount(roleMap.get(rsp.getCustomId()));
                }else {
                    rsp.setRoleCount(0);
                }
                //组装子账号数量信息
                if (subMap.containsKey(rsp.getCustomId())){
                    rsp.setSubCount(subMap.get(rsp.getCustomId()));
                }else {
                    rsp.setSubCount(0);
                }
                //组装策略数量
                if (strategyMap.containsKey(rsp.getCustomId())){
                    rsp.setStrategyCount(strategyMap.get(rsp.getCustomId()));
                }else{
                    rsp.setStrategyCount(0);
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
